<template>
  <div class="createPost-container">
    <el-form ref="postFormRef" :model="postForm" :rules="rules" class="form-container">
      <sticky :z-index="10" :class-name="'nav-c sub-navbar ' + postForm.status">
        <CommentDropdown v-model="postForm.comment_disabled" />
        <PlatformDropdown v-model="postForm.platforms" />
        <SourceUrlDropdown v-model="postForm.source_uri" />
        <el-button v-loading="loading" style="margin-left: 10px;" type="success" @click="submitForm">
          Publish
        </el-button>
        <el-button v-loading="loading" type="warning" @click="draftForm">
          Draft
        </el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-row>
          <Warning />
          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" prop="title">
              <MDinput v-model="postForm.title" :maxlength="100" name="name" required>
                Title
              </MDinput>
            </el-form-item>
            <div class="postInfo-container">
              <el-row>
                <el-col :span="8">
                  <el-form-item label-width="60px" label="Author:" class="postInfo-container-item">
                    <el-select v-model="postForm.author" :remote-method="getRemoteUserList" filterable default-first-option remote placeholder="Search user">
                      <el-option v-for="(item, index) in userListOptions" :key="item+index" :label="item" :value="item" />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="10">
                  <el-form-item label-width="120px" label="Publish Time:" class="postInfo-container-item">
                    <el-date-picker v-model="displayTime" type="datetime" format="yyyy-MM-dd HH:mm:ss" placeholder="Select date and time" />
                  </el-form-item>
                </el-col>

                <el-col :span="6">
                  <el-form-item label-width="90px" label="Importance:" class="postInfo-container-item">
                    <el-rate
                      v-model="postForm.importance"
                      :max="3"
                      :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                      :low-threshold="1"
                      :high-threshold="3"
                      style="display: inline-block; height: 20px;"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item style="margin-bottom: 40px;" label-width="70px" label="Summary:">
                <el-input v-model="postForm.content_short" :rows="1" type="textarea" class="article-textarea" autosize placeholder="Please enter the content" />
                <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}words</span>
              </el-form-item>

              <el-form-item prop="content" style="margin-bottom: 30px;">
                <Tinymce ref="editor" v-model="postForm.content" :height="480" width="100%" />
              </el-form-item>

              <el-form-item prop="image_uri" style="margin-bottom: 30px;">
                <Upload v-model="postForm.image_uri" />
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'ArticleDetail'
}
</script>

<script setup>
import { defineProps, ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'
import { useRoute } from 'vue-router'
import { useStore } from 'vuex'

import Tinymce from '@/components/Tinymce'
import Upload from '@/components/Upload/SingleImage3'
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky' // 粘性header组件
import { validURL } from '@/utils/validate'
import { fetchArticle } from '@/api/article'
import { searchUser } from '@/api/remote-search'
import Warning from './Warning'
import { CommentDropdown, PlatformDropdown, SourceUrlDropdown } from './Dropdown'

const defaultForm = {
  status: 'draft',
  title: '', // 文章题目
  content: '', // 文章内容
  content_short: '', // 文章摘要
  source_uri: '', // 文章外链
  image_uri: '', // 文章图片
  display_time: undefined, // 前台展示时刻
  id: undefined,
  platforms: ['a-platform'],
  comment_disabled: false,
  importance: 0
}

const route = useRoute()
const store = useStore()

const props = defineProps({
  isEdit: {
    type: Boolean,
    default: false
  }
})

const validateRequire = (rule, value, callback) => {
  if (value === '') {
    ElMessage({
      message: rule.field + '为必传项',
      type: 'error'
    })
    callback(new Error(rule.field + '为必传项'))
  } else {
    callback()
  }
}

const validateSourceUri = (rule, value, callback) => {
  if (value) {
    if (validURL(value)) {
      callback()
    } else {
      ElMessage({
        message: '外链url填写不正确',
        type: 'error'
      })
      callback(new Error('外链url填写不正确'))
    }
  } else {
    callback()
  }
}
const postFormRef = ref()
const postForm = ref(Object.assign({}, defaultForm))

const loading = ref(false)
const userListOptions = ref([])
const rules = reactive({
  image_uri: [{ validator: validateRequire }],
  title: [{ validator: validateRequire }],
  content: [{ validator: validateRequire }],
  source_uri: [{ validator: validateSourceUri, trigger: 'blur' }]
})
let tempRoute = reactive({})

const contentShortLength = computed(() => {
  return postForm.value.content_short.length
})

const displayTime = computed({
  // set and get is useful when the data
  // returned by the back end api is different from the front end
  // back end return => "2013-06-25 06:59:25"
  // front end need timestamp => 1372114765000
  get() {
    return (+new Date(postForm.value.display_time))
  },
  set(val) {
    postForm.value.display_time = new Date(val)
  }
})

const fetchData = id => {
  fetchArticle(id).then(response => {
    postForm.value = response.data
    // just for test
    postForm.value.title += `   Article Id:${postForm.value.id}`
    postForm.value.content_short += `   Article Id:${postForm.value.id}`
    // set tagsview title

    console.log()
    setTagsViewTitle()

    // set page title
    setPageTitle()
  })
}

const setTagsViewTitle = () => {
  const title = 'Edit Article'
  const route = Object.assign({}, tempRoute, { title: `${title}-${postForm.value.id}` })
  store.dispatch('tagsView/updateVisitedView', route)
}

const setPageTitle = () => {
  const title = 'Edit Article'
  document.title = `${title} - ${postForm.value.id}`
}

const submitForm = () => {
  postFormRef.value.validate(valid => {
    if (valid) {
      loading.value = true
      ElNotification({
        title: '成功',
        message: '发布文章成功',
        type: 'success',
        duration: 2000
      })
      postForm.value.status = 'published'
      loading.value = false
    } else {
      console.log('error submit!!')
      return false
    }
  })
}

const draftForm = () => {
  if (postForm.value.content.length === 0 || postForm.value.title.length === 0) {
    ElMessage({
      message: '请填写必要的标题和内容',
      type: 'warning'
    })
    return
  }

  ElMessage({
    message: '保存成功',
    type: 'success',
    showClose: true,
    duration: 1000
  })
  postForm.value.status = 'draft'
}

const getRemoteUserList = query => {
  searchUser(query).then(response => {
    if (!response.data.items) return
    userListOptions.value = response.data.item.map(v => v.name)
  })
}

onMounted(() => {
  if (props.isEdit) {
    const id = route.params && route.params.id
    fetchData(id)
  }

  tempRoute = Object.assign({}, route)
})

</script>

<style lang="scss" scoped>
@import "../../../styles/mixin";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea :deep(textarea) {
  padding-right: 40px;
  resize: none;
  border: none;
  box-shadow: none;
  border-radius: 0px;
  border-bottom: 1px solid #bfcbd9;
}

</style>

<style lang="scss">
.createPost-container {
  .nav-c {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    flex-direction: row;
  }
}

</style>
